package com.yyj.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 拦截器
 *
 * @author lzp
 *
 */
public class InvokeLogInterceptor implements HandlerInterceptor {
    /**
     * 发起请求,进入拦截器链，运行所有拦截器的preHandle方法，
     * 1.当preHandle方法返回false时，从当前拦截器往回执行所有拦截器的afterCompletion方法，再退出拦截器链。
     * 2.当preHandle方法全为true时，执行下一个拦截器,直到所有拦截器执行完。再运行被拦截的Controller。然后进入拦截器链，
     * 运行所有拦截器的postHandle方法,完后从最后一个拦截器往回执行所有拦截器的afterCompletion方法。
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有拦截器的afterCompletion方法
     */

    static Logger logger = LoggerFactory.getLogger(InvokeLogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        logger.info("=======================");
        String requestUrl = request.getRequestURI().toString();
        logger.info(requestUrl);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        if (ex != null) {
            logger.error("未处理异常", ex);
            PrintWriter out = response.getWriter();
            out.print("服务器内部错误:" + ex.getMessage());
        }

    }


}